<?php
class JavaScript {

	/**
	* Register javascript code for executing AJAX request for deleting item
	*/
    public static function deleteItem($message='Are you sure you want to delete this?', $element='.deleteItem') {
        Yii::app()->clientScript->registerCoreScript('yii');
        $script = <<<EOD
                function deleteItem(){
                    if (confirm('$message')) {
                        jQuery.yii.submitForm(this,this.href,{});
                    }
                    return false;
                }

                $("$element").click(deleteItem);
EOD;

        Yii::app()->clientScript->registerScript('delete', $script, CClientScript::POS_READY);
    }

    public static function makeAjaxSafe() {
        Yii::app()->log->routes['web']->enabled = false;
    }

	/**
	* Handle registeration of javascript file based on HTTP_X_REQUESTED_WITH.
	*/
    public static function registerScriptFile($url,$position='0'){
        if($_SERVER['HTTP_X_REQUESTED_WITH'] ? $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest' : false){
            echo "<script type=\"text/javascript\">$.getScript(\"".$url."\");</script>\n";

        }else{
            Yii::app()->clientScript->registerScriptFile($url, $position);
        }
    }

	/**
	* Handle registeration of piece of javascript code based on HTTP_X_REQUESTED_WITH.
	*/
    public static function registerScript($id,$script,$position=4){
        if($_SERVER['HTTP_X_REQUESTED_WITH'] ? $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest' : false){
            if($position==4){
                echo "<script type=\"text/javascript\">$(function(){".$script."}</script>\n";
            }
        }else{
            Yii::app()->clientScript->registerScript($id,$script,$position);
        }
    }

}
